<?php
class Timkiem extends Model
{
    public function getKetQua($param)
    {

        $sql = "SELECT * FROM dienthoai WHERE (1=1)";
        $bind = array();

        if (isset($param['hangsx']) && $param['hangsx'] !== 'null') {
            $sql .= ' AND hsx_id = :hsx_id';
            $bind['hsx_id'] = $param['hangsx'];
        }

        if (isset($param['gia']) && $param['gia'] != 'null') {
            $base = (int)$param['gia'];
            if ($base <= 1) {
                $sql .= ' AND dt_gia <= :price ';
                $bind['price'] = 6000;
            } elseif ($base >= 7) {
                $sql .= ' AND dt_gia > :price ';
                $bind['price'] = 16000;
            }
            else {
                $max = $base * 2000 + 4000;
                $min = $base * 2000 + 2000;

                $sql .= ' AND dt_gia  BETWEEN :min AND :max ';

                $bind['min'] = $min;
                $bind['max'] = $max;
            }

        }

        if (isset($param['ten'])) {
            $sql .= " AND CONVERT(dt_ten USING utf8) LIKE :ten";
            $bind['ten'] = '%' . $param['ten'] . '%';
        }

        $data = $this->Db->run($sql, $bind);
        return Dienthoai::format($data);

    }


    public function search($param)
    {
        $bind = array();
        $sql = <<<SQL
SELECT *
FROM dienthoai d NATURAL JOIN hangsanxuat h
WHERE
  CONVERT(d.dt_id USING utf8) LIKE :key OR
  CONVERT(d.dt_ten USING utf8) LIKE :key OR
  CONVERT(d.dt_gia USING utf8) LIKE :key OR
  CONVERT(h.hsx_id USING utf8) LIKE :key OR
  CONVERT(h.hsx_ten USING utf8) LIKE :key;
SQL;

        $bind['key'] = '%' . $param['key'] . '%';
        return $this->Db->run($sql, $bind);

    }
}